package advance.JVM.concurrent.test.test3;

import net.jcip.annotations.ThreadSafe;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * description： <br>
 * createTime: 2018/3/1517:12 <br>
 *
 * @author zzh
 */
@ThreadSafe
public class OneShotLatch {

    private final Sync sync = new Sync();


    public void signal() {
        sync.releaseShared(0);
    }


    public void await() throws InterruptedException {
        sync.acquireInterruptibly(0);
    }


    class Sync extends AbstractQueuedSynchronizer {

        @Override
        protected int tryAcquireShared(int arg) {
            return (getState() == 1) ? 1 : -1;
        }


        @Override
        protected boolean tryReleaseShared(int arg) {
            setState(1);
            return true;
        }
    }


    public static void main(String[] args) throws InterruptedException {
        OneShotLatch oneShotLatch = new OneShotLatch();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "begin");
                try {
                    oneShotLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "over");
            }).start();
        }

        System.out.println("------------------------");
        TimeUnit.SECONDS.sleep(5);
        oneShotLatch.signal();
        System.out.println("OVER");
    }
}
